package com.mingda.weathermagiccenter.controller;

import com.alibaba.fastjson.JSONObject;
import com.mingda.weathermagiccenter.config.hefengconfig.WeatherConfigBean;
import com.mingda.weathermagiccenter.config.hefengconfig.WindSpeedConfig;
import com.mingda.weathermagiccenter.config.riskconfig.*;
import com.mingda.weathermagiccenter.dto.AreaBean;
import com.mingda.weathermagiccenter.dto.StationBean;
import com.mingda.weathermagiccenter.mapper.CommMapper;
import com.mingda.weathermagiccenter.pojo.RiskBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.ssssssss.magicapi.core.service.MagicAPIService;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Tag(name = "风险评估V1", description = "风险评估V1")
@Slf4j
@RestController
@RequestMapping("/mdweatherapi")
public class AssessmentController {

    @Autowired
    private RiskConfigBean riskConfigBean;
    @Autowired
    MagicAPIService service;


    @Autowired
    CommMapper commMapper;

    @Operation(summary = "基于林地距离评估风险", description = "基于林地距离评估风险")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "500", description = "出现异常")
    })
    @GetMapping("getrisk")
    public ResponseEntity<RiskBean> getrisk(String lon, String lat, String slope) {
        List<Map<String,Object>>  list = commMapper.getDistance(Double.parseDouble(lon),Double.parseDouble(lat));
        RiskBean riskBean = new RiskBean();
        riskBean.setLon(Double.parseDouble(lon));
        riskBean.setLat(Double.parseDouble(lat));
        try {
            riskBean.setSlope(Float.parseFloat(slope));
        }
        catch (Exception e){
            slope = "0";
            riskBean.setSlope(0);
        }

        String time  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS") .format(new Date() );
        riskBean.setTime(time);
        StationBean stationBean = new StationBean();
        AreaBean areaBean = new AreaBean();
        if(list.size() > 0) {
            double distance = (Double) list.get(0).get("distance_m");
            riskBean.setDistance((float) distance);
            areaBean.setDistance((float) distance);
           // areaBean.setGeom((String)list.get(0).get("geom"));
          //  areaBean.setGeojson((String) list.get(0).get("geojson"));

            areaBean.setId((String)list.get(0).get("id"));
            areaBean.setClosetpoint((String)list.get(0).get("closest_point"));
            riskBean.setArea(areaBean);
        }


        Map<String, Object> params = new HashMap<>();
        // 注入变量信息
        params.put("lon",lon);
        params.put("lat",lat);
        params.put("num","1");
        params.put("stationtype","1"); //国家站数据
        // 内部调用接口不包含code以及message信息，同时也不走拦截器。
        List<LinkedHashMap> value = service.execute("GET", "/mdweatherapi/wsstationweathernearestfast", params);
        if(value!= null && value.size() > 0){
            stationBean = new StationBean();
            stationBean.setStationKey((String)value.get(0).get("stationkey"));
            stationBean.setStationName((String)value.get(0).get("stationname"));
            stationBean.setTemp((Float) value.get(0).get("temp"));
            stationBean.setTemp_min((Float) value.get(0).get("temp_min"));
            stationBean.setTemp_max((Float) value.get(0).get("temp_max"));
            stationBean.setHumi((Float) value.get(0).get("humi"));
            stationBean.setWin_10_dir((int)value.get(0).get("win_10_dir"));
            stationBean.setWin_10_vel((Float)value.get(0).get("win_10_vel"));
            stationBean.setPrec((float)value.get(0).get("prec"));
            stationBean.setTimeBase((String)value.get(0).get("time"));
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime btime = now.minusHours(24); // 当前时间的24小时之前

            // 时间格式化为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String btimeStr = btime.format(formatter); // 24小时前时间
            String etimeStr = now.format(formatter);   // 当前时间

            List<Map<String, Object>> pec24list = commMapper.getPec24(stationBean.getStationKey(),btimeStr,etimeStr);
            if(pec24list!=null && pec24list.size() > 0){
                stationBean.setPrec24((Float) pec24list.get(0).get("prec"));

            }
            riskBean.setWeather(stationBean);

        }
        //开始计算威胁值
        float baserisk = calculateRisk(riskConfigBean.getBaseThreatConfigs() , riskBean.getDistance());
        riskBean.setBaserisk(baserisk);

        float sloprisk = calculateRisk(riskConfigBean.getSlopThreatConfigs(),Double.parseDouble(slope));
        riskBean.setSloperisk(sloprisk);


        if(stationBean != null){
            float windrisk = calculateRisk(riskConfigBean.getWindThreatConfigs(),stationBean.getWin_10_vel());
            riskBean.setWindspeedrisk(windrisk);

            float rainrisk = calculateRisk(riskConfigBean.getRainThreatConfigs(),stationBean.getPrec24());
            riskBean.setRainrisk(rainrisk);



            float  dif = getTemperatureHumidityCoefficient(LocalTime.now());

            float temphum = calculateRisk(riskConfigBean.getTemHumThreatConfigs(),stationBean.getTemp() / stationBean.getHumi());

            riskBean.setTemphumrisk(temphum*dif);
        }

        float taotalrisk = baserisk * (1 + riskBean.getWindspeedrisk() + riskBean.getRainrisk() + riskBean.getTemphumrisk() + riskBean.getCoverrisk() + riskBean.getSloperisk() );

        if(taotalrisk > 1){
            taotalrisk = 1;
        }
         riskBean.setTotalrisk(taotalrisk);
         riskBean.setTotalrisktxt( calculateTotal(riskConfigBean.getTotalThreatConfigs(),taotalrisk).get("value") );
         riskBean.setRiskcolor(calculateTotal(riskConfigBean.getTotalThreatConfigs(),taotalrisk).get("color") );

        return ResponseEntity.ok(riskBean);
    }



    /**
     * 根据输入时间返回温湿比系数。
     * @param time 输入的时间
     * @return 温湿比系数
     */
    public static float getTemperatureHumidityCoefficient(LocalTime time) {

        // 日间时间段：6:00 - 18:00
        LocalTime startOfDay = LocalTime.of(6, 0);
        LocalTime endOfDay = LocalTime.of(18, 0);

        if (time.isAfter(startOfDay) && time.isBefore(endOfDay)) {
            return 1.2f; // 日间系数
        } else {
            return 0.8f; // 夜间系数
        }
    }



    /**
     * 计算威胁值
     * @param
     * @return
     */
    public float calculateRisk(List<? extends ThreatConfig> configs , double input){
        float result = 0;

        try{
            for (ThreatConfig config : configs) {
                if (config.getMin() < input && config.getMax() >= input) {
                    result = config.getValue();
                    break; // 找到匹配的配置，退出循环
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    public HashMap<String, String>  calculateTotal(List<TotalThreatConfig> configs , double input){
        HashMap<String,String> map = new HashMap<String,String>();
        String result = "";
        String color = "";
        try{
            for (TotalThreatConfig config : configs) {
                if (config.getMin() < input && config.getMax() >= input) {
                    result = config.getValue();
                    color = config.getColor();
                    break; // 找到匹配的配置，退出循环
                }
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

        map.put("value",result);
        map.put("color",color);
        return map;
    }


}
